<?php
namespace app\modules\cn\models;

use app\modules\exercise\models\ExerciseListDetail as ExerciseDetail;
use yii;
use yii\db\ActiveRecord;
use app\modules\cn\models\ExerciseCategory;

class ExerciseList extends ActiveRecord
{

    public static function tableName()
    {
        return '{{%exercise_list}}';
    }

    // $level = [
    //         '简单'=>1,
    //         '一般'=>2,
    //         '困难'=>3
    //     ];
    //     $type = [
    //         '填空题'=>1,
    //         '单选题'=>2,
    //         '多选题'=>3,
    //         '匹配题'=>4,
    //         '图形题'=>5
    //     ];

    //     $topic = [
    //         '求职'=>1,
    //         '活动介绍'=>2,
    //         '课题研究'=>3,
    //         '学术场景'=>4,
    //         '租房'=>5,
    //         '旅游'=>6,
    //         '改造建设'=>7,
    //         '医疗'=>8,
    //         '咨询申请'=>9,
    //         '银行'=>10,
    //         '图书馆'=>11
    //     ];


    /**
     * @Title  [获取听力剑雅真题分类]
     * @Author Don
     * @Date   2021-04-25
     * @return [type]
     */
    public function getListenList($cateIds, $show = 0)
    {
        $list = array();
        $data = array();
        // f_d($cateIds);
        $where = '';
        if ($show == 1) {
            $where .= ' AND isShow=1';
        }
        foreach ($cateIds as $value) {
            $res = Yii::$app->db->createCommand("SELECT cate_id,name from {{%exercise_category}} where pid=$value $where")->queryAll();
            foreach ($res as $k => $v) {
                if ($v['name'] == '难度') {
                    unset($res[$k]);
                }
            }
            //三级列表名
            $data[] = $res;
            $list[] = $this->getlistenexerciserealnum($value);
        }

        // f_d($list);
        // $listreal = $this->getlistenexerciserealnumdate($real);
        //四级列表内容
        // array_push($list, $listreal);

        return array($data, $list);
    }

    public function getlistenexerciserealnum($id)
    {
        $list = ExerciseCategory::find()->select('cate_id')->where("pid=$id AND isShow=1")->distinct()->asArray()->All();
        $list = array_column($list, 'cate_id');
        $data = [];
        if (!empty($list)) {
            // 查询重复标题
            foreach ($list as $value) {
                $tmp = self::find()->select(['name'])->where(['cate_id' => $value, 'pid' => 0])->distinct()->asArray()->All();
                $res[$value] = array_column($tmp, 'name');
            }
            // 过滤重复标题
            foreach ($res as $k => $v) {
                $doc = [];
                foreach ($v as $vc) {
                    $dov = self::find()->select('id,cate_id,pid,content_id,image,name,title,sort,viewCount,show,catName,level,type,topic,test_site,title_image')->where(['name' => $vc, 'cate_id' => $k])->asArray()->One();
                    $doc[] = $dov;
                }

                $data[$k] = $doc;
            }
        }
        return $data;
    }

    public function getlistenexerciserealnumdate($id)
    {

        $list = ExerciseCategory::find()->select('cate_id')->where("pid=$id AND isShow=1")->distinct()->asArray()->All();
        $vlist = array_column($list, 'cate_id');
        // 查询重复标题
        foreach ($vlist as $vid) {
            $doing = self::find()->select(['name'])->where(['cate_id' => $vid, 'pid' => 0])->distinct()->asArray()->All();
            $exc = array_column($doing, 'name');
            $vdate[$vid] = $exc;
        }

        // 过滤重复标题
        foreach ($vdate as $kid => $vdd) {
            $doc = '';
            $date = '';
            foreach ($vdd as $vc) {
                $dov = self::find()->where(['name' => $vc, 'cate_id' => $kid])->asArray()->One();
                $doc[] = $dov;
            }
            $date = Yii::$app->db->createCommand("SELECT id,name from {{%exercise_category}} where cate_id=$kid")->queryAll();
            $name = $date[0]['name'];
            $vue[$name] = $doc;
        }
        return $vue;
    }

    // 雅思听力 听力剑真 --- 做题详细分组----辅助方法
    //by:sjeam
    public function getlistenexercisedotest($ids)
    {
        $res = self::find()->select(['cate_id', 'name'])->where(['content_id' => $ids, 'pid' => 0])->asArray()->one();
        $vid = $res['cate_id'];
        $name = $res['name'];

        $data = self::find()->where(['cate_id' => $vid, 'name' => $name])->asArray()->all();

        return $data;
    }

    /**
     * @Title  [获取读写列表]
     * @Author Don
     * @Date   2021-04-27
     * @param  [type]
     * @return [type]
     */
    public function getReadList($cate_id)
    {
        $list = self::find()->select('cate_id,content_id,name,catName,viewCount')->where(['cate_id' => $cate_id])->distinct()->asArray()->all();
        // f_d($list);
        foreach ($list as $key => $value) {
            // $tmp = self::find()->where(['cate_id'=>$value['cate_id'], 'name'=>$value['name']])->asArray()->one();
            // $content_id = $tmp['content_id'];
            // $list[$key]['content_id'] = $tmp['content_id'];
            $tmp = explode('-', $value['name']);
            $list[$key]['test_name'] = $tmp[0];
            $list[$key]['passage_name'] = $tmp[1];
        }
        // f_d($list);
        // 判断是否做完
        $list = $this->progressRate($list);
        // f_d($list);
        $data = [];
        foreach ($list as $key => $value) {
            if (array_key_exists($value['test_name'], $data)) {
                $data[$value['test_name']][] = $value;
            } else {
                $data[$value['test_name']][] = $list[$key];
            }
        }
        // f_d($data);
        return $data;
    }

    /**
     * @Title  [判断阅读的整体test是否完成]
     * @Author Don
     * @Date   2021-04-28
     * @param  [type]
     * @return [type]
     */
    public function progressRate($data)
    {
        // f_d($data);
        $userId = Yii::$app->session->get('userId');
        foreach ($data as $k => $v) {
            $data[$k]['userFinish'] = 0;
            $data[$k]['correctRate'] = 0;
            // 查询分类和名字下所有content_id
            $pid = self::find()->asArray()->select('content_id')->where('name=\'' . $v['name'] . "' and cate_id=" . $v['cate_id'])->all();
            // f_d($pid);
            $pid = implode(',', array_column($pid, 'content_id'));
            // f_d($pid);
            // 查询content_id为pid的所有题数
            $data[$k]['count'] = count(ExerciseDetail::find()->asArray()->select('content_id')->where('pid in(' . $pid . ")")->all());
            if ($userId == false) { // 用户未登陆
                $data[$k]['isOver'] = 0;
                $data[$k]['continue'] = 0;
                $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid=' . $v['content_id'])->orderBy('content_id asc')->one()['content_id'];
                $data[$k]['resultid'] = '';

            } else { // 用户已登陆
                // $userId = 4;
                $resultid = Yii::$app->db->createCommand("select resultid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pid . ") and userId=$userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0 group by resultid order by id desc")->queryOne();
                if ($resultid != false) {
                    $record = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pid . ") and userId=$userId and resultid=" . $resultid['resultid'] . " and ISNULL(answer)=0 and LENGTH(trim(answer))>0 order by id desc")->queryAll();//倒序的后改为正序
                    if ($data[$k]['count'] <= count($record)) {//数目相同，表示本章节完成
                        $data[$k]['isOver'] = 1;
                        $data[$k]['continue'] = 0;
                        $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid=' . $v['content_id'])->orderBy('content_id asc')->one()['content_id'];
                        $data[$k]['startPid'] = ExerciseDetail::find()->asArray()->select('pid')->where('content_id=' . $data[$k]['startId'])->orderBy('content_id asc')->one()['pid'];
                        $data[$k]['resultid'] = $resultid['resultid'];
                    } else {//继续做题
                        $data[$k]['isOver'] = 0;
                        $data[$k]['continue'] = 1;
//                        $data[$k]['startId'] = Content::find()->asArray()->select('id')->where('pid in (' . $pid . ') and id>' . $record[0]['testid'])->orderBy('id asc')->one()['id'];//原来按组做题
                        $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid in (' . $pid . ')')->orderBy('content_id asc')->one()['content_id'];//按短文
                        $data[$k]['startPid'] = $data[$k]['startId'] == false ? '' : ExerciseDetail::find()->asArray()->select('pid')->where('content_id=' . $data[$k]['startId'])->orderBy('content_id asc')->one()['pid'];
                        $data[$k]['resultid'] = $resultid['resultid'];
                    }
                    $data[$k]['userFinish'] = count($record); // 用户已完成数量
                } else {//开始做题
                    $data[$k]['isOver'] = 0;
                    $data[$k]['continue'] = 0;
                    $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid=' . $v['content_id'])->orderBy('content_id asc')->one()['content_id'];
                    $data[$k]['startPid'] = '';
                    $data[$k]['resultid'] = '';
                }
            }

            $data[$k]['nameTest'] = substr($v['name'], strrpos('-', $v['name']), 5);
            $total = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pid . ")  order by id desc")->queryAll();
            $true = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pid . ")  and result=1 order by id desc")->queryAll();
            $data[$k]['correctRate'] = (count($true) != false && count($total) != false) ? round(count($true) / count($total) * 100, 2) : 0;

        }
        // f_d($data);
        return $data;
    }

    /**
     * @Title  [获取写作列表]
     * @Author Don
     * @Date   2021-04-28
     * @param  [type]
     * @return [type]
     */
    public function getWriteList($cateIds, $show = 0)
    {
        $list = array();
        $data = array();
        // f_d($cateIds);
        $where = '';
        if ($show == 1) {
            $where .= ' AND isShow=1';
        }
        foreach ($cateIds as $value) {
            $res = Yii::$app->db->createCommand("SELECT cate_id,name from {{%exercise_category}} where pid=$value $where")->queryAll();
            foreach ($res as $k => $v) {
                if ($v['name'] == '难度') {
                    unset($res[$k]);
                }
            }
            //三级列表名
            $data[] = $res;
            $list[] = $this->getlistenexerciserealnum($value);
        }

        // f_d($list);
        // $listreal = $this->getlistenexerciserealnumdate($real);
        //四级列表内容
        // array_push($list, $listreal);

        return array($data, $list);
    }

    /**
     * @Title  [获取写作题目]
     * @Author Don
     * @Date   2021-04-28
     * @return [type]
     */
    public function getWriteQuestion($content_id, $cate_id)
    {
        $res = self::find()->where(['content_id' => $content_id, 'cate_id' => $cate_id])->asArray()->one();
        return $res;
    }

    /**
     * @Title  [获取题目详情]
     * @Author Don
     * @Date   2021-04-28
     * @return [type]
     */
    public function getWriteQuestionDetail($content_id, $cate_id)
    {
        $res = ExerciseDetail::find()->where(['pid' => $content_id, 'cate_id' => $cate_id])->asArray()->one();
        return $res;
    }

    /**
     * @Title  [获取说列表]
     * @Author Don
     * @Date   2021-04-29
     * @param  [type]
     * @return [type]
     */
    public function getSpeakList($cate_id)
    {
        $res = self::find()->select('id,cate_id,content_id,name,title,image,viewCount,catName,title_image')->where(['cate_id' => $cate_id])->asArray()->all();

        return $res;
    }

    /**
     * @Title  [title]
     * @Author Don
     * @Date   2021-04-30
     * @return [type]
     */
    public function getListenListByCate($cate, $cate_id, $category_id)
    {
        $list = ExerciseCategory::find()->where(['pid' => $cate_id])->asArray()->all();

        $list = array_column($list, 'cate_id');
// f_d($category_id);

        if ($cate == 'topic') {
            $res = self::find()->select('id,cate_id,content_id,name,title,image,catName,viewCount,title_image')->where(['topic' => $category_id])->andWhere(['in', 'cate_id', $list])->groupBy('name')->orderBy('id asc')->asArray()->all();
        } elseif ($cate == 'level') {
            $res = self::find()->select('id,cate_id,content_id,name,title,image,catName,viewCount,title_image')->where(['level' => $category_id])->andWhere(['in', 'cate_id', $list])->groupBy('name')->orderBy('id asc')->asArray()->all();
        } elseif ($cate == 'type') {
            $res = self::find()->select('id,cate_id,content_id,name,title,image,catName,viewCount,title_image')->where(['type' => $category_id])->andWhere(['in', 'cate_id', $list])->groupBy('name')->orderBy('id asc')->asArray()->all();
        }

        return $res;
    }

    /**
     * @Title  [title]
     * @Author Don
     * @Date   2021-04-30
     * @param  [type]
     * @param  [type]
     * @param  [type]
     * @return [type]
     */
    public function getReadListByCate($cate, $cate_id, $category_id)
    {
        $list = ExerciseCategory::find()->where(['pid' => $cate_id])->asArray()->all();
        // f_d($list);
        $list = array_column($list, 'cate_id');
        // f_d($list);
        if ($cate == 'topic') {
            $res = self::find()->select('id,cate_id,content_id,name,title,image,catName,viewCount,topic,title_image')->where(['topic' => $category_id])->andWhere(['in', 'cate_id', $list])->groupBy('name')->orderBy('id asc')->asArray()->all();
        } elseif ($cate == 'level') {
            $res = self::find()->select('id,cate_id,content_id,name,title,image,catName,viewCount,level,title_image')->where(['level' => $category_id])->andWhere(['in', 'cate_id', $list])->groupBy('name')->orderBy('id asc')->asArray()->all();
        } elseif ($cate == 'type') {
            $res = self::find()->select('id,cate_id,content_id,name,title,image,catName,viewCount,type,title_image')->where(['type' => $category_id])->andWhere(['in', 'cate_id', $list])->groupBy('name')->orderBy('id asc')->asArray()->all();
        }

        return $res;
    }

    // 判断听力的整体test是否完成
    //by:sjeam
    public function listenProgressRate($data, $catId)
    {
        $userId = Yii::$app->session->get('userId');
        foreach ($data as $k => $v) {
            if ($v != false) {
                $data[$k]['userFinish'] = 0;
                $data[$k]['correctRate'] = 0;
                $data[$k]['userFinish'] = 0;
                $tem = self::find()->asArray()->where('name="' . $v['name'] . '" and cate_id=' . $v['cate_id'])->all();
                $pids = implode(',', array_column($tem, 'content_id'));
                $name = str_replace(' - ', '-', str_replace('剑雅', 'jy', $v['name']));
                $data[$k]['id'] = $v['content_id'];
                $data[$k]['catId'] = $v['cate_id'];
                $data[$k]['nameTest'] = substr($name, strrpos($name, '-') - 5, 5);
                $data[$k]['count'] = count(ExerciseDetail::find()->asArray()->select('id')->where('pid in (' . $pids . ')')->all());
                if ($userId == false) {
                    $data[$k]['isOver'] = 0;
                    $data[$k]['continue'] = 0;
                } else {
                    $newid = Yii::$app->db->createCommand("select newid from {{%ielts_test_result}} where fid=" . $catId . " and pid =" . $v['content_id'] . " and userId=$userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0 group by newid order by id desc")->queryOne();
                    if ($newid != false) {
                        $record = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $catId . " and pid in (" . $pids . ") and userId=$userId and newid=" . $newid['newid'] . " and ISNULL(answer)=0 and LENGTH(trim(answer))>0 order by id desc")->queryAll();
                        if ($data[$k]['count'] <= count($record)) {//数目相同，表示本章节完成
                            $data[$k]['isOver'] = 1;
                            $data[$k]['continue'] = 0;
                        } else {//继续做题
                            $data[$k]['isOver'] = 0;
                            $data[$k]['continue'] = 1;
                        }
                        $data[$k]['userFinish'] = count($record);
                    } else {//开始做题
                        $data[$k]['isOver'] = 0;
                        $data[$k]['continue'] = 0;
                    }
                }
                $total = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pids . ")  order by id desc")->queryAll();
                $true = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pids . ")  and result=1 order by id desc")->queryAll();
                $data[$k]['correctRate'] = (count($true) != false && count($total) != false) ? round(count($true) / count($total) * 100, 2) : 0;
            }
        }
        return $data;
    }

    /**
     * [getlabeldelete 格式化]
     * @Author don
     * @Date   2021-08-03
     * @param  [type]     $dats [description]
     * @return [type]           [description]
     */
    public function getlabeldelete($dats)
    {
        $pregs = '/<p[^>]*>(.*)<\/p>/U';
        preg_match_all($pregs, $dats, $rel);
        return $rel[1];
    }

    /**
     * [listenFormat 听力数据格式的修改统一]
     * @Author don
     * @Date   2021-08-03
     * @param  [type]     $data [description]
     * @return [type]           [description]
     */
    public function listenFormat($data)
    {
        $userId = \Yii::$app->session->get('userId');
//        $userId=765;
        foreach ($data as $k => $v) {
            if ($v['parent']['description'] != false) {
                if ($v['parent']['article'] != false) {
                    $data[$k]['parent']['description'] = str_replace(['&lt;link/&gt;', '<link/>', '&lt;link &gt;', '<link />'], $v['parent']['article'], $v['parent']['description']);
                }
                $data[$k]['parent']['description'] = str_replace(['&lt;input/&gt;', '<input/>', '&lt;link &gt;', '<input />'], '#&', $data[$k]['parent']['description']);
                if ($v['parent']['image'] != false) {
                    $data[$k]['parent']['description'] = str_replace(['&lt;img/&gt;', '<img/>', '&lt;img &gt;', '<img />'], '<img src="https://ielts.thinkwithu.com' . $v['parent']['image'] . '"', $data[$k]['parent']['description']);
                }
            }
            $data[$k]['parent']['listeningFile'] = $v['parent']['listeningFile'] != false ? $this->getlabeldelete($v['parent']['listeningFile']) : array();
            $data[$k]['parent']['listeningFile'] = self::fileUrl($data[$k]['parent']['listeningFile']);
            if (count($data[$k]['parent']['listeningFile']) == 2) {//去掉第一个听力
                unset($data[$k]['parent']['listeningFile'][0]);
                $data[$k]['parent']['listeningFile'] = array_values($data[$k]['parent']['listeningFile']);
            }
            $tem = trim(substr($v['parent']['title'], strrpos($v['parent']['title'], ' ')));
            $temnum = $start = substr($tem, 0, strrpos($tem, '-'));
            foreach ($v['son'] as $key => $val) {
                $tmp = ExerciseResult::find()->asArray()->where("testid={$val['content_id']} and userid=$userId and typeid=1")->orderBy('id desc')->one();  //typeid=1为听 听阅写口
                if (!empty(@$tmp['answer'])) {
                    $data[$k]['son'][$key]['my_answer'] = $tmp['answer'];
                    $data[$k]['son'][$key]['judge'] = $tmp['result'];
                } else {
                    $data[$k]['son'][$key]['my_answer'] = '';
                    $data[$k]['son'][$key]['judge'] = '';
                }
                $data[$k]['son'][$key]['answer'] = $val['answer'] != false ? $this->getlabeldelete($val['answer']) : array();
                if ($val['name'] != '多选题' && $val['name'] != '配对选择题') {
                    $data[$k]['son'][$key]['qNum'] = $temnum;
                    $temnum = $temnum + 1;
                } else {
                    $data[$k]['son'][$key]['qNum'] = $temnum . '-' . (($temnum + strlen($val['alternatives'])) - 1);
                    $temnum = $temnum + strlen($val['alternatives']);
                }
            }
        }
        return $data;
    }

    /**
     * [readformat 格式化阅读数据]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function readformat($data)
    {
        foreach ($data as $k => $v) {
            if ($v['parent']['sentenceNumber'] != false) {
                $data[$k]['parent']['sentenceNumber'] = explode("<br />", nl2br($v['parent']['sentenceNumber']));
            } else {
                $data[$k]['parent']['sentenceNumber'] = array();
            }
            if ($v['parent']['description'] != false) {
                $tem = '';
                if ($v['parent']['type'] == 8 && $v['parent']['numbering'] == 8) {
                    $search = array('/<span class="answer-fill".*?>(.*?)<\/span>/is', '/&lt;span class="answer-fill".*?&gt;(.*?)&lt;\/span&gt;/is');
                    $tem = preg_replace($search, '#&', $v['parent']['description']);
                    if (!is_array($tem)) {
                        $tem = self::articleformat($tem);
                        $data[$k]['parent']['description'] = $tem != false ? $tem : $v['parent']['description'];
                    }
                }
                if ($v['parent']['type'] == 6 && $v['parent']['numbering'] == 6) {
                    $search = array('/<span class="answer-fill".*?>(.*?)<\/span>/is', '/&lt;span class="answer-fill".*?&gt;(.*?)&lt;\/span&gt;/is');
                    $tem = preg_replace($search, '#&', $v['parent']['article']);
                    if (!is_array($tem)) {
                        $data[$k]['parent']['article'] = $tem != false ? $tem : $v['parent']['article'];
                    }
                }
                if ($v['parent']['type'] == 10 && $v['parent']['numbering'] == 2) {
                    $search = array('/<input.*?>/is', '/&lt;input.*?&gt/is');
                    $tem = preg_replace($search, '#&', $v['parent']['article']);
                    if (!is_array($tem)) {
                        $data[$k]['parent']['article'] = $tem != false ? $tem : $v['parent']['article'];
                    }
                }
            } else {
                $data[$k]['parent']['description'] = array();
                if ($v['parent']['type'] == 6 && $v['parent']['numbering'] == 6) {
                    $search = array('/<span class="answer-fill".*?>(.*?)<\/span>/is', '/&lt;span class="answer-fill".*?&gt;(.*?)&lt;\/span&gt;/is');
                    $tem = preg_replace($search, '#&', $v['parent']['article']);
                    if (!is_array($tem)) {
                        $data[$k]['parent']['article'] = $tem != false ? $tem : $v['parent']['article'];
                    }
                }
                if ($v['parent']['type'] == 10 && $v['parent']['numbering'] == 6) {
                    $search = array('/<span class="answer-fill".*?>(.*?)<\/span>/is', '/&lt;span class="answer-fill".*?&gt;(.*?)&lt;\/span&gt;/is');
                    $tem = preg_replace($search, '#&', $v['parent']['article']);
                    if (!is_array($tem)) {
                        $data[$k]['parent']['article'] = $tem != false ? $tem : $v['parent']['article'];
                    }
                }

                if ($v['parent']['type'] == 10 && $v['parent']['numbering'] == 2) {
                    $search = array('/<input.*?>/is', '/&lt;input.*?&gt/is');
                    $tem = preg_replace($search, '#&', $v['parent']['article']);
                    if (!is_array($tem)) {
                        $data[$k]['parent']['article'] = $tem != false ? $tem : $v['parent']['article'];
                    }
                }
            }
            foreach ($v['son'] as $key => $val) {
                if ($val['description'] != false) {
                    $data[$k]['son'][$key]['description'] = explode("<br />", nl2br($val['description']));
                } else {
                    $data[$k]['son'][$key]['description'] = array();
                }
            }
        }
        return $data;
    }

    /**
     * 阅读文章
     * @param $article
     * @return mixed|string
     */
    public static function articleformat($article)
    {
        $article = str_replace(["\r\n", "\r"], "\n", $article);
        $content = explode("\n", $article);
        $letterArr = range('A', 'Z');
        foreach ($content as $k => $v) {
            $sub = substr(ltrim($v), 0, 2);
            $letter = trim($sub);
            if (!$letter) continue;
            if (in_array($letter, $letterArr)) {
                //段落ABCD加粗
                $content[$k] = '<strong>' . $sub . '</strong>' . substr(ltrim($v), 2);
            }
        }
        $article = implode('<br>', $content);
        //$article = str_replace("<br>",'<br><br>',$article);
        $article = str_replace('</p>', '</p><br>', $article);
        return $article;
    }

    // 总  --听 说读写  排行榜
    //by:sjeam
    public function getlistentestorder($typeid)
    {
        $userId = Yii::$app->session->get('userId');
        // var_dump($typeid);
        if ($typeid == 0) {
            // 改变 总榜排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
            // var_dump($totals);
            // var_dump($allnum);
        } else if ($typeid == 1) {
            // 改变 听总排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        } else if ($typeid == 2) {
            // 改变 说总排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        } else if ($typeid == 3) {
            // 改变 读总排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        } else if ($typeid == 4) {
            // 改变 写总排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        }
        // 取testid  降维
        // $numbers= array_column($totals,'testid');
        // $num=count($numbers);
        $testorder = RankingOrder::find()->where(['userid' => $userId, 'typeid' => $typeid])->distinct()->asArray()->All();

        if (!empty($testorder)) {
            $id = $testorder[0]['id'];
            Yii::$app->db->createCommand()->update('{{%ielts_test_order}}', [
                // 'userId' => $userId,
                'order' => $percentage,
                // 'typeid'=>5,
            ], 'id=' . $id)->execute();
        } else {
            Yii::$app->db->createCommand()->insert('{{%ielts_test_order}}', [
                'userid' => $userId,
                'typeid' => $typeid,
                'order' => $percentage
            ])->execute();
        }
        //   var_dump($num);
        return true;
    }

    public static function fileUrl($data)
    {
        foreach ($data as $k => $v) {
            if (!stristr($v, 'http')) {
                $data[$k] = 'https://ielts.thinkwithu.com' . $v;
            }
        }
        return $data;
    }

    /**
     * @Title  判断模考是否完成
     * @Author Yoyo
     * @Date   2023-04-28
     */
    public function MockData($where, $num)
    {
        $data = ExerciseList::find()->distinct()->select('x2_exercise_list.name,x2_exercise_list.cate_id,content_id')->asArray()->leftJoin('x2_exercise_category', 'x2_exercise_list.cate_id=x2_exercise_category.cate_id')->where("$where and x2_exercise_category.isShow=1")->groupby('name,cate_id')->orderby('x2_exercise_list.id asc')->all();//听力
        $list = array_chunk($data, $num);
        return $list;
    }
    /**
     * @Title  [判断模考是否完成]
     * @Author Yoyo
     * @Date   2023-04-28
     */
//    public function MockRate($data)
//    {//全部模考和局部模考进度
//        $uid = Yii::$app->session->get('uid');
//        foreach ($data as $k => $v) {
//            $data[$k]['isOver'] = $data[$k]['continue'] = $data[$k]['time'] = 0;
//            $data[$k]['startId'] = $v[0]['content_id'];
//            $name = '(name ="' . implode('" or name="', array_column($v, 'name')) . '")';
//            $pid = ExerciseList::find()->asArray()->select('content_id')->where("$name and cate_id=" . $v[0]['cate_id'])->all();
//            $pid = implode(',', array_column($pid, 'content_id'));// 查询content_id为pid的所有题数
//            $data[$k]['count'] = count(ExerciseDetail::find()->asArray()->select('content_id')->where('pid in(' . $pid . ")")->all());
//            if ($uid != false) { // 用户已登陆
//                $mockData = MockPublic::find()->asArray()->where('content_id=' . $v[0]['content_id'] . ' and cate_id=' . $v[0]['cate_id'] . ' and uid=' . $uid)->one();//超过半小时的中断就变成未完成
//                if ($mockData != false) {
//                    if ($mockData['status'] == false) {//未完成
//                        $detailData = MockDetail::find()->asArray()->where('pub_id=' . $mockData['id'] . ' and uid=' . $uid)->orderby('id desc')->all();
//                        if ($detailData != false && (time() - $detailData[0]['createTime']) < 1800) { //这里有中断的情况,最后一题距离现在的时间是都超过半小时
//                            $data[$k]['continue'] = 2;//中断
//                            $data[$k]['time'] = 1800 - (time() - $detailData['createTime']);
//                            $data[$k]['startId'] = array_values(array_diff(array_column($data, 'content_id'), array_column($detailData, 'content_id')))[0];//id
//                        } else {
//                            $data[$k]['continue'] = 1;//未完成
//                        }
//                    } else {
//                        $data[$k]['isOver'] = 1;
//                    }
//                }
//                //开始的题目id
////                $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid=' . $v[0]['content_id'])->orderBy('content_id asc')->one()['content_id'];
//
//            }
//        }
//        return $data;
//    }

    /**
     * @Title  [判断模考是否完成]
     * @Author Yoyo
     * @Date   2023-04-28
     */
    public function MockRate($data, $type = 1)
    {//全部模考和局部模考进度 resultid比较重要实测的时候注意
        $uid = Yii::$app->session->get('uid');
        foreach ($data as $k => $v) {
            $public = MockPublic::find()->select('count(id) as count,avg(endTime-startTime) as avgTime ')->asArray()->where('mockcate_id=' . $v['id'] . ' and type=' . $type . ' and status!=0')->one();
            $data[$k]['number'] = $public != false ? $public['count'] : 0;
            $data[$k]['avgTime'] = $public != false ? floor($public['avgTime'] / 60) . 'm' . ($public['avgTime'] % 60) . 's' : 0;
            $data[$k]['isOver'] = $data[$k]['continue'] = $data[$k]['time'] = 0;
            $data[$k]['startType'] = $type==1?'listen':($type==2?'read':'');
            if ($type == 1) {//听力
                $pid = $v['listen'];
            } elseif ($type == 2) {//阅读
                $pid = $v['read'];
            } else {
                $pid = $v['listen'] . ',' . $v['read'] . ',' . $v['write'];
            }
            $data[$k]['startId'] = explode(',', $pid)[0];
            $data[$k]['count'] = count(ExerciseDetail::find()->asArray()->select('content_id')->where('pid in (' . $pid . ")")->all());
            $pidData = \app\modules\exercise\models\ExerciseList::find()->asArray()->select('catName,name')->where('content_id in (' . $pid . ")")->one();
            $data[$k]['catName'] = $pidData['catName'];
            $data[$k]['test'] =  strtoupper(substr(stristr(str_replace(' ','',$pidData['name']),'test'),0,5));
            if ($uid != false) { // 用户已登陆
                $mockData = MockPublic::find()->asArray()->where('mockcate_id=' . $v['id'] . ' and uid=' . $uid . ' and type=' . $type)->orderBy('id desc')->one();//超过半小时的中断就变成未完成
                if ($mockData != false) {
                    if ($mockData['status'] == false) {//做题中
                        $detailData = MockDetail::find()->asArray()->where('pub_id=' . $mockData['id'] . ' and uid=' . $uid)->orderby('id desc')->all();
                        $data[$k]['continue'] = 1;//中断
                        if ($detailData == false) {
                            $data[$k]['time'] = 1800;
                            $data[$k]['startType'] = $type!=2?'listen':'read';
                        } else {
                            $data[$k]['time'] = 1800 - (time() - $detailData[0]['createTime']);
                            $data[$k]['startId'] = array_values(array_diff(explode(',', $pid), array_column($detailData, 'content_id')))[0];//id
                            $startQueation= ExerciseList::find()->asArray()->select('cate_id')->where('content_id='.$data[$k]['startId'])->one();
                            if ($startQueation['cate_id'] < 423 || $startQueation['cate_id'] == 700 || $startQueation['cate_id'] == 701)
                                $data[$k]['startType'] = 'listen';
                            if (($startQueation['cate_id'] > 465 && $startQueation['cate_id'] < 475) || $startQueation['cate_id'] == 718 || $startQueation['cate_id'] == 719)
                                $data[$k]['startType'] = 'read';
                            if (($startQueation['cate_id'] > 514 && $startQueation['cate_id'] < 523) || $startQueation['cate_id'] == 720 || $startQueation['cate_id'] == 721)
                                $data[$k]['startType'] = 'write';
                        }
                    } elseif ($mockData['status'] == 1) {
                        $data[$k]['isOver'] = 1;
                    } elseif ($mockData['status'] == 2) {//未完成
                        $data[$k]['continue'] = 2;
                        $data[$k]['isOver'] = 1;//中断
                    }
                }
            }
        }
        return $data;
    }

    /**
     * [listenFormat 听力数据格式的修改统一]
     * @Author yoyo
     * @Date   2023-05-03
     * @param  [type]     $data [description]
     * @return [type]           [description]
     */
    public function listenMockFormat($data,$pub_id)
    {
        $uid = \Yii::$app->session->get('uid');
        foreach ($data as $k => $v) {
            if ($v['parent']['description'] != false) {
                if ($v['parent']['article'] != false) {
                    $data[$k]['parent']['description'] = str_replace(['&lt;link/&gt;', '<link/>', '&lt;link &gt;', '<link />'], $v['parent']['article'], $v['parent']['description']);
                }
                $data[$k]['parent']['description'] = str_replace(['&lt;input/&gt;', '<input/>', '&lt;link &gt;', '<input />'], '#&', $data[$k]['parent']['description']);
                if ($v['parent']['image'] != false) {
                    $data[$k]['parent']['description'] = str_replace(['&lt;img/&gt;', '<img/>', '&lt;img &gt;', '<img />'], '<img src="https://ielts.thinkwithu.com' . $v['parent']['image'] . '"', $data[$k]['parent']['description']);
                }
            }
            $data[$k]['parent']['listeningFile'] = $v['parent']['listeningFile'] != false ? $this->getlabeldelete($v['parent']['listeningFile']) : array();
            $data[$k]['parent']['listeningFile'] = self::fileUrl($data[$k]['parent']['listeningFile']);
            if (count($data[$k]['parent']['listeningFile']) == 2) {//去掉第一个听力
                unset($data[$k]['parent']['listeningFile'][0]);
                $data[$k]['parent']['listeningFile'] = array_values($data[$k]['parent']['listeningFile']);
            }
            $tem = trim(substr($v['parent']['title'], strrpos($v['parent']['title'], ' ')));
            $temnum = $start = substr($tem, 0, strrpos($tem, '-'));
            foreach ($v['son'] as $key => $val) {
                $tmp = MockAnswer::find()->asArray()->where("content_id={$val['content_id']} and uid=$uid and pub_id=$pub_id")->orderBy('id desc')->one();  //typeid=1为听 听阅写口
                if (!empty(@$tmp['answer'])) {
                    $data[$k]['son'][$key]['my_answer'] = $tmp['answer'];
                    $data[$k]['son'][$key]['judge'] = $tmp['result'];
                } else {
                    $data[$k]['son'][$key]['my_answer'] = '';
                    $data[$k]['son'][$key]['judge'] = '';
                }
                $data[$k]['son'][$key]['answer'] = $val['answer'] != false ? $this->getlabeldelete($val['answer']) : array();
                if ($val['name'] != '多选题' && $val['name'] != '配对选择题') {
                    $data[$k]['son'][$key]['qNum'] = $temnum;
                    $temnum = $temnum + 1;
                } else {
                    $data[$k]['son'][$key]['qNum'] = $temnum . '-' . (($temnum + strlen($val['alternatives'])) - 1);
                    $temnum = $temnum + strlen($val['alternatives']);
                }
            }
        }
        return $data;
    }
}
